<template>
    <div id="mainDiv" style="width:100%;height:1000px"></div>
</template>

<script>
import * as echarts from 'echarts';
import * as api from "@/api";


export default {
  name:"",

  data(){
    return{
      carModelType:[],
      carNumByType:[],
      carSingNumByType:[],
      totalNum:"",
      totalSingNum:"",
      params:{
        orderByColumn:"carModelName"
      },
      option : {
        title: {
          text: '车辆库存统计',
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        calculable: true,
        xAxis: {type: 'value',},
        yAxis: {type: 'category'},
      }
    }
  },
  created() {
  },
  methods:{
    initMyChart(){
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(document.getElementById('mainDiv'));
      myChart.setOption(this.option);
      // 绘制图表
      let totalNum = 0;
      let totalSingNum = 0;
      api.getCarInfoByType(this.params).then((res)=>{
        res.data.carTypeNum.forEach((item)=>{
          this.carModelType.push(item.name);
        });
        res.data.carNumByType.forEach((item)=>{
          this.carNumByType.push(item.value);
          totalNum += item.value;
        });
        res.data.carSingNumByType.forEach((item)=>{
          this.carSingNumByType.push(item.value);
          totalSingNum += item.value;
        });
        myChart.setOption({
          legend: {
            data: ['车型下全部车辆', '在店车辆'],
            formatter: function(name) {
              if(name === "车型下全部车辆"){
                return name+"（"+totalNum+"）";
              }else if(name === "在店车辆"){
                return name+"（"+totalSingNum+"）";
              }
            }
          },
          xAxis: {type: 'value'},
          yAxis: {
            type: 'category',
            data: this.carModelType
          },
          grid: {
            left: '50',            // 固定左边刻度宽度
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          series: [
            {
              name: '车型下全部车辆',
              type: 'bar',
              data: this.carNumByType,
            },
            {
              name: '在店车辆',
              type: 'bar',
              data: this.carSingNumByType,
            },
          ]
        })
      })

    },
  },

  mounted(){
    this.initMyChart();
  }
}

</script>
